/*
 * IC Project - a prototype to test a hypothesis of collective intelligence
 * Copyright (C) 2012 Paolo Conte - paolo@concavi.net
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This code is derived from the project ojoverse (2008, same author)
 * under the license GPL2. See <http://www.gnu.org/licenses/>.
 */

package org.ix.utils;

import java.io.*;
import java.net.*;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ix.data.entities.P2PMessage;
import org.ix.net.p2p.commands.Helo;

public class Network {

    public static String displayInterfaceInformation() {
        StringBuffer sbNetInt = new StringBuffer(900);
        try {
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)) {
                sbNetInt.append("Display name: ").append(netint.getDisplayName()).append("\n");
                sbNetInt.append("Name: ").append(netint.getName()).append("\n");
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    sbNetInt.append("InetAddress: ").append(inetAddress).append("\n");
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(Helo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return sbNetInt.toString();
    }

    /**
     * @deprecated @param host
     * @param port
     * @return
     */
    public static String readSocket(String host, int port) {
        Socket socket = null;
        String message = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(10 * 1000);
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
            out.println("GET /index.html HTTP/1.1");
            out.println();
            out.flush();

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String inputLine;
            int count = 0;

            while ((inputLine = in.readLine()) != null) {
                count++;
                message += count;
                message += inputLine;
                message += "\n";
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                in.close();
                out.close();
                socket.close();
            } catch (IOException ex) {
                Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return message;
    }

    public static String readURLContent(URL url) {
        String ret = "";
        URLConnection urlConn = null;
        InputStream in = null;
        BufferedReader br = null;

        try {
            urlConn = url.openConnection();
            urlConn.setConnectTimeout(1000);
            urlConn.setReadTimeout(3000);
            urlConn.setRequestProperty("X-Requested-With", "IC-P2P");
            urlConn.setRequestProperty("User-Agent", "IC");
            urlConn.setRequestProperty("Accept-Charset", "UTF-8");
            urlConn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");

            urlConn.setDoInput(true);
            urlConn.setUseCaches(false);

            in = urlConn.getInputStream();

            // without URLConnection (stream from URL):
            //br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));

            String inputLine;

            while ((inputLine = br.readLine()) != null) {
                ret += inputLine;
            }

        } catch (IOException ex) {
            Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return ret;
    }

    public static P2PMessage parseP2PMessage(String action, String string) {
        if (string == null || string.length() == 0 || string.indexOf(":") == 0) {
            String content = "";
            if (string != null) {
                if (string.length() > 500) {
                    content = string.substring(0, 500);
                } else {
                    content = string;
                }
            }
            return new P2PMessage(P2PMessage.RESPONSE_KO, P2PMessage.RESPONSE_TYPE_ERROR, content);
        }
        String type = string.substring(0, string.indexOf(":"));
        String content = string.substring(string.indexOf(":") + 1);
        String status = "";
        if (type.equals(P2PMessage.RESPONSE_TYPE_ERROR) || type.equals(P2PMessage.RESPONSE_KO)) {
            status = P2PMessage.RESPONSE_KO;
        } else if (type.equals(P2PMessage.RESPONSE_TYPE_REPLY) || type.equals(P2PMessage.RESPONSE_OK)) {
            status = P2PMessage.RESPONSE_OK;
        }

        return new P2PMessage(action, status, type, content);
    }

    public static void main(String[] args) throws Exception {
        URL url = new URL("http", "localhost", 8084, "/ic/p2p/helo");
        //URL url = new URL("http", "sys.jellylab.net", 80, "/server.php");
        String msg = Network.readURLContent(url);
        System.out.println(msg.replaceAll("<br>", "\n"));
        System.out.println(parseP2PMessage("HELO", msg));
    }
}
